package com.zx.idc.backend.gui.scheduler.sys;

import com.zx.idc.backend.gui.sys.service.SysBackupLogServiceOfFtp;
import com.zx.idc.common.util.JsonUtil;
import com.zx.idc.common.util.LocalDateTimeFormatUtil;
import com.zx.idc.ds.sys.bean.DataBackupSetting;
import com.zx.idc.ds.sys.bean.OffSiteBackupSetting;
import com.zx.idc.ds.sys.entity.SysBackupLog;
import com.zx.idc.ds.sys.entity.SysConfiguration;
import com.zx.idc.ds.sys.service.ISysConfigurationService;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;

/**
 * 执行备份的 job
 *
 * @author rxliuli
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class DataBackupJob implements Job {
    @Autowired
    private ISysConfigurationService sysConfigurationService;
    @Autowired
    private SysBackupLogServiceOfFtp sysBackupLogServiceOfFtp;

    @Override
    public void execute(JobExecutionContext context) {
        final Integer userId = (Integer) context.getMergedJobDataMap().get("userId");
        final LocalDateTime now = LocalDateTime.now();
        final SysBackupLog sysBackupLog = new SysBackupLog(userId + " 自动备份: " + LocalDateTimeFormatUtil.formatLocalDateTime(now, "yyyy-MM-dd hh:mm:ss"), now, userId);
        final SysConfiguration sysConfiguration = sysConfigurationService.selectOne(new SysConfiguration().setConfigKey(OffSiteBackupSetting.OFF_SITE_BACKUP_SETTING_CONFIG_KEY));
        final OffSiteBackupSetting offSiteBackupSetting = JsonUtil.read(sysConfiguration.getConfigValue(), OffSiteBackupSetting.class);
        sysBackupLogServiceOfFtp.addBackup(sysBackupLog, offSiteBackupSetting, new DataBackupSetting());
    }
}
